#include "Ctrl/AddNewPackageCtrlCmd.hpp"
#include "Ctrl/ControlCenter.hpp"
#include "Storage/ConnectionConfig.hpp"
#include "Storage/StorageFactory.hpp"
#include "Storage/StorageCommand.hpp"
#include "Storage/ProjectStorage.hpp"
#include "Storage/PackageStorage.hpp"
#include "Model/Package.hpp"
#include <cassert>

namespace Ctrl
{
	

AddNewPackageCtrlCmd::AddNewPackageCtrlCmd( 
		ControlCenter& ctrlCenter, Model::Package* pParentPackage, Model::Package* pNewPackage )
	: ControlCommand( ctrlCenter)
	, pParentPackage_( pParentPackage)
	, pNewPackage_( pNewPackage)
{
	assert( NULL != pParentPackage);
	assert( NULL != pNewPackage);
}

// ---------------------------------------------------------------------------------------------------------------------

void AddNewPackageCtrlCmd::undo() 
{
	pParentPackage_->removeChildPackage( pNewPackage_);
	rCtrlCenter_.packageController().announcePackageRemoved( pParentPackage_, pNewPackage_);
	// Take care of the storage, too
	Storage::StorageFactory& storageFactory = Ctrl::ControlCenter::instance().prjController().storageFactory();
	Storage::StorageCommand* pTopCommand = storageFactory.getPackageStorage().topCommand();
	if( NULL != pTopCommand 
			&& pNewPackage_ == &pTopCommand->subject() 
			&& Storage::StorageCommand::Create == pTopCommand->type())
	{
		// We have in the top of the storage commands the opposite of this one. Se we should just remove the 
		//	previous command.
		storageFactory.getPackageStorage().popCommand();
		delete pTopCommand;
	}
	else
	{
		// The command in the storage command list was not created with the execute method of this class.
		storageFactory.getPackageStorage().pushCommand( storageFactory.createPackageRemovalCommand( * pNewPackage_));
	}
}

// ---------------------------------------------------------------------------------------------------------------------

void AddNewPackageCtrlCmd::execute() 
{
	pParentPackage_->addNewPackage( pNewPackage_);
	rCtrlCenter_.packageController().announceNewPackageAdded( pParentPackage_, pNewPackage_);
	// Take care of the storage, too
	Storage::StorageFactory& storageFactory = Ctrl::ControlCenter::instance().prjController().storageFactory();
	storageFactory.getPackageStorage().pushCommand( storageFactory.createPackageCreationCommand( *pNewPackage_));
}

} // namespace Ctrl
